import Dep from "./dep.js";
export const reactive = (obj) => {
  let dep = new Dep();
  return deepProxy(obj, {
    get: function (target, key, receiver) {
      // 在这里添加观察者对象 Dep.target 表示观察者
      Dep.target && dep.addSub(Dep.target);
      return Reflect.get(target, key, receiver);
    },
    set: function (target, key, value, receiver) {
      // 判断旧值和新值是否相等
      if (target[key] === value) return true;

      const ret = Reflect.set(target, key, value, receiver);
      // 触发通知 更新视图
      dep.notify();
      return ret;
    },
  });
};

function deepProxy(target, handler) {
  if (typeof target !== "object" || target === null) {
    throw new Error("Target must be an object");
  }

  if (Array.isArray(target)) {
    target = target.slice();
  } else {
    target = { ...target };
  }

  for (let key in target) {
    if (typeof target[key] === "object" && target[key] !== null) {
      target[key] = deepProxy(target[key], handler);
    }
  }

  return new Proxy(target, handler);
}
